<template>
  <div id="organizePage" @click="bodyClick">
    <HeadNav type="inquire" ref="head" :show="1"></HeadNav>
    <div class="wd-1220">
      <div class="clearfix">
        <div class="float-left">
          <SlideNav type="inquire" sort="goods"></SlideNav>
        </div>
        <div class="float-right">
          <div class="main-container" v-if="powerType == 1">
            <div class="model-container">
              <div
                class="model-bg"
                style="min-height: 660px; padding-bottom: 75px"
              >
                <div class="section-title">
                  品种列表
                  <span class="desc" v-if="total > 0">共{{ trueTotal>2000?2000+'+':trueTotal }}个品种</span>
                </div>
                <div style="padding: 20px 15px">
                  <div class="clearfix">
                    <div class="float-left">
                      <a-cascader
                        :field-names="{
                          label: 'name',
                          value: 'category_id',
                          children: 'child_list',
                        }"
                        :options="categoryList"
                        placeholder="所有类目"
                        change-on-select
                        :allowClear="false"
                        expand-trigger="hover"
                        style="width: 280px"
                        v-model="chooseCategory"
                        @change="selectCategory"
                      />
                    </div>
                    <div
                      class="float-left"
                      style="width: 300px; margin-left: 10px"
                    >
                      <a-input placeholder="搜索品种ISBN" v-model="isbn" />
                    </div>
                    <div
                      class="float-left"
                      style="width: 300px; margin-left: 10px"
                    >
                      <a-input placeholder="搜索品种名称" v-model="goodsName" />
                    </div>
                  </div>
                  <div class="clearfix" style="margin-top: 10px">
                    <div class="float-left">
                      <a-auto-complete
                        option-label-prop="value"
                        style="width: 280px"
                        placeholder="搜索作者"
                        @search="onSearchAuthor"
                        :defaultActiveFirstOption="false"
                        v-model="authorInput"
                        @blur="authorBlur"
                        @select="selectedAuthor"
                      >
                        <template slot="dataSource">
                          <a-select-option
                            v-for="(opt, index) in dataSourceAuthor"
                            :key="index"
                            :value="opt.name"
                          >
                            <div class="result">
                              <span>{{ opt.name }}</span>
                            </div>
                          </a-select-option>
                        </template>
                      </a-auto-complete>
                    </div>
                    <div class="float-left" style="margin-left: 10px">
                      <a-auto-complete
                        option-label-prop="value"
                        style="width: 300px"
                        placeholder="搜索供应商名称"
                        @search="onSearchSupplier"
                        :defaultActiveFirstOption="false"
                        v-model="supplierInput"
                        @blur="supplierBlur"
                        @select="selectedSupplier"
                      >
                        <template slot="dataSource">
                          <a-select-option
                            v-for="(opt, index) in dataSourceSupplier"
                            :key="index"
                            :value="opt.name"
                          >
                            <div class="result">
                              <span>{{ opt.name }}</span>
                            </div>
                          </a-select-option>
                        </template>
                      </a-auto-complete>
                    </div>
                    <div
                      class="float-left"
                      style="width: 300px; margin-left: 10px"
                    >
                      <a-select
                        mode="multiple"
                        v-model="keyWords"
                        style="width: 100%"
                        :filter-option="false"
                        placeholder="选择标签"
                        @search="fetchTag"
                        @change="handleChange"
                      >
                        <a-spin
                          v-if="fetching"
                          slot="notFoundContent"
                          size="small"
                        />
                        <a-select-option
                          v-for="kitem in tagList"
                          :key="kitem.tag_id"
                          >{{ kitem.tag_name }}</a-select-option
                        >
                      </a-select>
                    </div>
                  </div>
                </div>
                <div style="text-align: center; margin-bottom: 20px">
                  <a-button
                    type="primary"
                    style="width: 120px"
                    @click="onSearch"
                    >搜索</a-button
                  >
                  <a-button
                    style="margin-left:5px;"
                    @click="onReset"
                    >重置条件</a-button
                  >
                  <a-button
                    style="margin-left:5px;"
                    loading
                    v-if="uploading"
                    >导出数据</a-button
                  >
                  <a-button
                    style="margin-left:5px;"
                    @click="addUpload"
                    v-else
                    >导出数据</a-button
                  >
                </div>
                <div class="table" v-if="goodsList">
                  <table style="table-layout: fixed">
                    <colgroup>
                      <col width="280" />
                      <col width="100" />
                      <col width="120" />
                      <col width="120" />
                      <col width="160" />
                      <col width="90" />
                      <col width="90" />
                      <col width="80" />
                    </colgroup>
                    <thead>
                      <tr>
                        <td>品种信息</td>
                        <td>供应商</td>
                        <td>作者</td>
                        <td>类目</td>
                        <td>标签</td>
                        <td style="text-align: right">销售层级</td>
                        <td style="text-align: right">书龄</td>
                        <td style="text-align: right">操作</td>
                      </tr>
                    </thead>
                    <tbody v-if="goodsList.length > 0">
                      <tr v-for="(item, index) in goodsList" :key="index">
                        <td>
                          <div class="goods-desc">
                            <div
                              v-if="item.cover_pic"
                              style="width: 60px; height: 60px"
                            >
                              <img
                                :src="item.cover_pic"
                                alt
                                style="width: 60px; height: 60px"
                              />
                            </div>
                            <span
                              v-else
                              class="no-pic"
                              style="min-width: 60px; min-height: 60px"
                            ></span>
                            <div class="goods-info" style="height: 60px">
                              <div
                                class="click-font goods-name"
                                :title="item.title"
                                @click="$toDetail(item.goods_id)"
                              >
                                {{ item.title }}
                              </div>
                              <div style="margin-left: 5px">
                                <span class="data-tab data-tab-eleven" v-if="item.sale_type == '滞销品种' || item.sale_type == '停售品种'">{{item.sale_type}}</span>
                                <span class="data-tab data-tab-eight" v-else-if="item.sale_type == '畅销品种'">{{item.sale_type}}</span>
                                <span class="data-tab data-tab-ten" v-else-if="item.sale_type">{{item.sale_type}}</span>
                                <span v-if="item.isbn" class="data-tab data-tab-eleven">{{
                                  item.isbn
                                }}</span>
                              </div>
                            </div>
                          </div>
                        </td>
                        <td>
                          {{ item.supplier_name }}
                        </td>
                        <td>
                          <div class="author">
                            <div
                              class="author-name"
                              v-if="item.authors.length == 0"
                            >
                              {{ item.author }}
                            </div>
                            <div
                              class="author-name click-font"
                              v-if="item.authors.length == 1"
                              @click.stop="$toAuthor(item.authors[0].author_id)"
                            >
                              {{ item.author }}
                            </div>
                            <div
                              class="author-name click-font"
                              v-if="item.authors.length > 1"
                              @click.stop="openAuthor(item, index)"
                            >
                              {{ item.author }}
                            </div>
                            <div class="author-list" v-if="item.active">
                              <div v-if="item.authors.length > 0">
                                <div
                                  class="author-item click"
                                  v-for="(aitem, aindex) in item.authors"
                                  :key="aindex"
                                  @click.stop="$toAuthor(aitem.author_id)"
                                >
                                  {{ aitem.name }}
                                </div>
                              </div>
                              <div v-else>
                                <div class="author-item">
                                  未查询到对应作者信息
                                </div>
                              </div>
                            </div>
                          </div>
                        </td>
                        <td>
                          <span>{{ item.cate_node_2 }}</span
                          ><span v-if="item.cate_node_3"
                            >>{{ item.cate_node_3 }}</span
                          ><span v-if="item.cate_node_4"
                            >>{{ item.cate_node_4 }}</span
                          >
                        </td>
                        <td>
                          <div v-if="item.tag_list.length > 0">
                            <span
                            v-for="(litem, lindex) in item.tag_list"
                            :key="lindex"
                            >{{ litem.tag_name
                            }}<template
                              v-if="lindex !== item.tag_list.length - 1"
                              >；</template
                            ></span>
                          </div>
                          <div v-else>--</div>
                        </td>
                        <td style="text-align: right">
                          <div class="main-font">{{item.dms}}</div>
                          <div>{{item.month_sale_text}}</div>
                        </td>
                        <td style="text-align: right">
                          <div class="main-font">{{item.sale_age_text}}</div>
                          <div>{{item.publish_date}}</div>
                        </td>
                        <td style="text-align: right">
                          <span
                            class="click-font"
                            v-if="item.focus_id"
                            @click="focusHandle('cancel', item)"
                            >取消自选</span
                          >
                          <span
                            class="click-font"
                            v-else
                            @click="focusHandle('add', item)"
                            >自选</span
                          >
                        </td>
                      </tr>
                    </tbody>
                    <tbody v-else>
                      <tr>
                        <td colspan="8" style="text-align: center">
                          <div style="margin-top: 100px"><a-empty /></div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                <!-- 分页 -->
                <div class="page" v-if="goodsList">
                  <a-pagination
                    :show-total="(total) => `共 ${trueTotal>2000?2000+'+':trueTotal} 条数据`"
                    :default-current="1"
                    :total="total"
                    :defaultPageSize="page_size"
                    v-model="page"
                    @change="onShowSizeChange"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="main-container" v-else>
            <div class="model-container">
              <div
                class="model-bg"
                style="
                  min-height: 660px;
                  padding-bottom: 75px;
                  position: relative;
                "
              >
                <PageNoPower></PageNoPower>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <Loading ref="load" :show="1" :isLoading="isLoading"></Loading>
  </div>
</template>
<style scoped lang="scss" src="@/style/scss/pages/admin/index.scss"></style>
<script>
import {
  QUERY_GOODS_SEARCH,
  QUERY_GOODS_SEARCH_TAG,
  INDUSTRY_AUTHOR_LISTS,
  QUERY_GOODS_SEARCH_EXPORT
} from "../../apis/inquire.js";
import {
  COMPETE_MONITOR_SELF_ADD,
  COMPETE_MONITOR_SELF_DELETE,
} from "../../apis/compete.js";
import { COMMON_CATEGORY, SUPPLIER_GETS } from "../../apis/common.js";
export default {
  data() {
    return {
      powerType: 1,
      goodsCount: 0,
      page: 1,
      page_size: 20,
      trueTotal: 0,
      total: 0,
      goodsList: [],
      inputVal: "",
      searchLoading: false,
      isLoading: true,
      categoryList: [],
      chooseCategory: [0],
      isbn: "",
      goodsName: "",
      authorID: 0,
      supplierID: 0,
      keyWords: [],
      dataSourceAuthor: [],
      dataSourceSupplier: [],
      tagList: [],
      fetching: false,
      authorInput:"",
      lastAuthor:"",
      lastSupplier:"",
      supplierInput:"",
      uploading: false,
    };
  },
  mounted() {
    this.powerType = this.$refs.head.accountInfo.type;
    this.goodsCount = this.$refs.head.accountInfo.goods_count;
    if (this.powerType == 1) {
      // this.getData()
    }
    this.getFirstCategory();
  },
  updated() {},
  methods: {
    // 获取列表数据
    async getData() {
      var tStamp = this.$getTimeStamp();
      let data = {
        organization_id: this.$refs.head.publishInfo.organization_id,
        cate_id: this.chooseCategory[this.chooseCategory.length - 1],
        isbn: this.isbn,
        title: this.goodsName,
        author_id: this.authorID,
        supplier_id: this.supplierID,
        tags: this.keyWords.join(","),
        sort:"publish_date",
        page: this.page,
        page_size: this.page_size,
        search: this.inputVal,
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res = await QUERY_GOODS_SEARCH(data);
      if (res.code == 0) {
        this.goodsList = [];
        this.trueTotal = res.data.count;
        this.total = res.data.count > 2000 ?2000:res.data.count;
        res.data.lists.map((value, key) => {
          value.active = false;
          this.goodsList.push(value);
        });
        this.$nextTick(()=>{
          this.isLoading = false;
        })
      } else {
        this.isLoading = false;
        this.total = 0;
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    // 获取初级分类列表
    async getFirstCategory() {
      var tStamp = this.$getTimeStamp();
      let data = {
        // floor: 2,
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res = await COMMON_CATEGORY(data);
      if (res.code == 0) {
        this.categoryList = [];
        let _data = {
          category_id: 0,
          name: "所有类目",
          pid: 0,
        };
        this.categoryList.push(_data);
        res.data.map((value, key) => {
          this.categoryList.push(value);
        });
        this.isLoading = false;
      } else {
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    // 自选操作
    async focusMonitor(type, id) {
      var tStamp = this.$getTimeStamp();
      let data = {
        supplier_id: this.$refs.head.publishInfo.supplier_id,
        organization_id: this.$refs.head.publishInfo.organization_id,
        goods_id: id,
        focus_id: id,
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res;
      if (type == "add") {
        res = await COMPETE_MONITOR_SELF_ADD(data);
      } else if (type == "cancel") {
        res = await COMPETE_MONITOR_SELF_DELETE(data);
      }
      if (res.code == 0) {
        if (type == "add") {
          this.$refs.head.globalTip(2, "添加成功", 0);
        } else if (type == "cancel") {
          this.$refs.head.globalTip(2, "取消成功", 0);
        }
        this.getData();
      } else {
        if (res.code == 105) {
          this.$refs.head.globalTip(1, "该商品已关注，请勿重复添加", 0);
        } else {
          this.$refs.head.globalTip(1, res.message, res.code);
        }
      }
    },
    // 作者列表获取
    async getAuthorList(val) {
      var tStamp = this.$getTimeStamp();
      let data = {
        page: 1,
        page_size: 100,
        timestamp: tStamp,
        name: val,
      };
      data.sign = this.$getSign(data);
      let res = await INDUSTRY_AUTHOR_LISTS(data);
      if (res.code == 0) {
        this.dataSourceAuthor = [];
        res.data.list.map((value, key) => {
          let _obj = value;
          _obj.name = value.name + "（" + value.author_id + "）";
          this.dataSourceAuthor.push(_obj);
        });
      } else {
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    // 供应商列表获取
    async getSupplierList(val) {
      var tStamp = this.$getTimeStamp();
      let data = {
        page: 1,
        page_size: 100,
        timestamp: tStamp,
        supplier_name: val,
      };
      data.sign = this.$getSign(data);
      let res = await SUPPLIER_GETS(data);
      if (res.code == 0) {
        this.dataSourceSupplier = [];
        res.data.list.map((value, key) => {
          let _obj = value;
          _obj.name = value.supplier_name + "（" + value.supplier_id + "）";
          this.dataSourceSupplier.push(_obj);
        });
      } else {
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    // 标签列表获取
    async getTagList(val) {
      var tStamp = this.$getTimeStamp();
      let data = {
        timestamp: tStamp,
        search: val,
      };
      data.sign = this.$getSign(data);
      let res = await QUERY_GOODS_SEARCH_TAG(data);
      if (res.code == 0) {
        this.tagList = [];
        this.tagList = res.data.result;
        this.fetching = false;
      } else {
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    // 添加下载任务
    async addUpload(){
      if(this.goodsList.length == 0){
        this.$refs.head.globalTip(1,"数据为空，无法导出！", 0);
        return;
      }
      var tStamp = this.$getTimeStamp();
      let data = {
        organization_id: this.$refs.head.publishInfo.organization_id,
        cate_id: this.chooseCategory[this.chooseCategory.length - 1],
        isbn: this.isbn,
        title: this.goodsName,
        author_id: this.authorID,
        supplier_id: this.supplierID,
        tags: this.keyWords.join(","),
        sort:"publish_date",
        page: this.page,
        page_size: this.page_size,
        search: this.inputVal,
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res = await QUERY_GOODS_SEARCH_EXPORT(data);
      if (res.code == 0) {
        let _this = this;
        this.$confirm({
          title: "数据导出中",
          content: "数据表格文件正在生成中，前往数据导出任务列表下载",
          okText: "前去下载",
          cancelText: "取消",
          okType: "primary",
          onOk() {
            _this.$router.push({name:"dataupload"});
          },
          onCancel() {}
        });
      } else {
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    focusHandle(type, item) {
      let _this = this;
      if (type == "add") {
        this.$confirm({
          title: "确认添加关注",
          content: "确认将《" + item.title + "》添加至自选关注？",
          okText: "确定",
          cancelText: "取消",
          okType: "primary",
          onOk() {
            _this.focusMonitor(type,item.goods_id);
          },
          onCancel() {},
        });
      } else if(type == 'cancel'){
        this.$confirm({
          title: "确认取消关注",
          content: "确认取消关注《" + item.title + "》？",
          okText: "确定",
          cancelText: "取消",
          okType: "primary",
          onOk() {
            _this.focusMonitor(type,item.focus_id);
          },
          onCancel() {},
        });
      }
    },
    selectCategory() {},
    // 供应商
    onSearchSupplier(value) {
      let _value = value.toString();
      this.dataSourceSupplier = [];
      this.getSupplierList(_value);
    },
    // 选中供应商
    selectedSupplier(value) {
      this.dataSourceSupplier.map((val, key) => {
        if (val.name == value) {
          this.supplierID = val.supplier_id;
          this.lastSupplier = value;
        }
      });
    },
    // 作者
    onSearchAuthor(value) {
      let _value = value.toString();
      this.dataSourceAuthor = [];
      this.getAuthorList(_value);
    },
    authorBlur(value){
      if(this.authorInput != this.lastAuthor){
        this.authorInput = "";
        this.authorID = 0;
        this.dataSourceAuthor = [];
      }
    },
    supplierBlur(value){
      if(this.supplierInput != this.lastSupplier){
        this.supplierInput = "";
        this.supplierID = 0;
        this.dataSourceSupplier = [];
      }
    },
    // 选中作者
    selectedAuthor(value) {
      this.dataSourceAuthor.map((val, key) => {
        if (val.name == value) {
          this.authorID = val.author_id;
          this.lastAuthor = value;
        }
      });
    },
    // 搜索标签
    fetchTag(value) {
      if (value.length > 0) {
        this.fetching = true;
        this.getTagList(value);
      } else {
        this.tagList = [];
      }
    },
    // 选中标签
    handleChange(value) {
      this.keyWords = value;
    },
    onSearch(value) {
      this.page = 1;
      this.isLoading = true;
      setTimeout(()=>{
        this.getData();
      },500);
    },
    onShowSizeChange(page, pageSize) {
      this.page = page;
      this.isLoading = true;
      setTimeout(()=>{
        this.getData();
      },500);
    },
    bodyClick() {
      if (this.goodsList) {
        this.goodsList = this.goodsList.map((value) => {
          value.active = false;
          return value;
        });
      }
    },
    openAuthor(item, index) {
      this.goodsList = this.goodsList.map((value, key) => {
        if (index == key) {
          value.active = true;
        } else {
          value.active = false;
        }
        return value;
      });
    },
    // 重置条件
    onReset(){
      this.chooseCategory = [0];
      this.inputVal = "";
      this.isbn = "";
      this.goodsName = "";
      this.authorID = 0;
      this.supplierID = 0;
      this.keyWords = [];
      this.supplierInput = "";
      this.authorInput = "";
      this.dataSourceAuthor = [];
      this.dataSourceSupplier = [];
      this.tagList = [];
    }
  },
};
</script>
